// 天地图
<template>
  <div class="mapPosition-root">
    <div class="top">
      <el-autocomplete
        class="search-input"
        v-model="address"
        @change="changeAddress"
        :disabled="disabled"
        clearable
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false"
        @select="handleSelect"
      ></el-autocomplete>
      <div class="gps">
        <div>经度：{{ gpsX }}</div>
        <div class="gps-li">纬度：{{ gpsY }}</div>
      </div>
      <!-- <el-button class="select-map" type="primary" size="mini">获取地址</el-button> -->
    </div>
    <div class="amap" :id="'amap'+mapId"></div>
  </div>
</template>

<script>
const TiandituKey = '3fe9702883d7aade9e3638c1b2779f80'
import { throttle } from '@/utils/assist.js'
import axios from "axios";
import { isArray, isUndefined, isString, isNumber, isNil, toString, merge, cloneDeep } from "lodash-es";

export default {
  props: {
    initMapData: {
      type: Object,
      default: () => {
        return {
          address: "",
          gpsX: "",
          gpsY: "",
          towncode: "",
        };
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      mapId: Math.random().toString(36).substr(2), //地图的DOM id不要固定，否则一个页面有两个地图时，第二张地图会不显示
      address: "",
      gpsX: "",
      gpsY: "",
      towncode: "",
      wxMap: null,
    };
  },
  watch: {
    initMapData: {
      handler(newVal, oldVal) {
        if (newVal) {
          console.log('watch',newVal)
          if(!newVal.gpsX||!newVal.gpsY){
            return;
          }
          this.address = newVal.address;
          this.gpsX = newVal.gpsX;
          this.gpsY = newVal.gpsY;
					this.towncode = newVal.towncode;
          if(!this.wxMap){
            // console.log('watch')
            this.initwxMap();
          }else{
            this.updateMap();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods:{
      changeAddress(e){
         this.address = e;
        this.postEmit();
      },
      // 通知父组件
      postEmit(){
        let areaCode = []
        let towncode =  this.towncode.substring(3)
        // if(this.towncode){
        //   areaCode.push(this.towncode.substr(0,2).padEnd(12,'0'))
        //   let cityCode = this.towncode.substr(0,4).padEnd(12,'0')
        //   areaCode.push(cityCode)
        //   let subIndex = this.getCountySubIndex(cityCode)
        //   areaCode.push(this.towncode.substr(0,subIndex).padEnd(12,'0'))
        // }
        // console.log('towncode==',towncode)
         if(towncode){
          areaCode.push(towncode.substr(0,2).padEnd(12,'0'))
          let cityCode = towncode.substr(0,4).padEnd(12,'0')
          areaCode.push(cityCode)
          let subIndex = this.getCountySubIndex(cityCode)
          towncode = towncode.substr(0,subIndex).padEnd(12,'0')
          areaCode.push(towncode)
        }
        //  console.log('areaCode==',towncode,areaCode)
        let pramas = {
          address: this.address,
          gpsX: this.gpsX,
          gpsY: this.gpsY,
          towncode,
          areaCode,
        };
        this.$emit("changeAddress", pramas);
      },
       getCountySubIndex(cityCode){
        // 中山、东莞截取10位
        let filterList = ['442000000000','441900000000']
        if(filterList.findIndex(t=>t==cityCode)>-1){
          return 10;
        }
        return 6;
      },
      initwxMap(){
         let T = window.T;
        //  console.log('init','amap'+this.mapId)
         if(this.wxMap){
          // 如果有地图实例，就不再new Map，免得出现两个地图
          return
        }
        // console.log('new map',this.wxMap)
        this.wxMap = new T.Map('amap'+this.mapId); // div的id
        // 传参中心点经纬度，以及放大程度，最小1，最大18
        this.wxMap.centerAndZoom(new T.LngLat(113.94318, 23.25722), 8);
        var cp = new T.CoordinatePickup(this.wxMap, {
          callback: (lnglat)=>{
            // console.log('click')
            this.setMaker(lnglat)
          }
        });
        cp.addEvent();
        //鹰眼
        // let miniMap = new T.Control.OverviewMap({
        //   isOpen: true,
        //   size: new T.Point(150, 150)
        // });
        // this.wxMap.addControl(miniMap);
      },
       // 根据经纬度获取地址，并且发起emit通知父组件
      async getGeocoderFun(lon, lat) {
        // let T = window.T;
        // let geocoder = new T.Geocoder();
        // geocoder.getLocation(new T.LngLat(lon, lat), (result) => {
        //   console.log('result===Tmap====',result)

        //   this.address = result.getAddress();
        //   this.gpsX = lon
        //   this.gpsY = lat
        //   this.towncode = result.addressComponent.county_code || ''
        //   this.postEmit();
        // });
        axios({
        method: "get",
        url: `https://api.tianditu.gov.cn/geocoder?postStr={"lon":${lon},"lat":${lat},"appkey":"8a7b9aac0db21f9dd995e61a14685f05","ver":"1"}&type=geocode&tk=${TiandituKey}`,
        headers: {
          // "Content-Type": "application/x-www-form-urlencoded",
          "Content-Type": "application/json",
        },
      }).then(res => {
        console.log('TTTTTTTTT====',res)
        let result = res.data.result
        this.address = result.formatted_address
        this.gpsX = lon
        this.gpsY = lat
        this.towncode = result.addressComponent.county_code || ''
         this.postEmit();
      })
      },
      // 根据经纬度,绘制标注点
      getLngLat(lnglat) {
        // console.log('getLngLat',lnglat.lng)
        let T = window.T;
        let x = lnglat.lng;
        let y = lnglat.lat;
        if(isString(lnglat.lng) === false){
          x = lnglat.lng.toFixed(6);
          y = lnglat.lat.toFixed(6);
        }
        this.wxMap.clearOverLays(); // 清空原来的标注点
        let point = new T.LngLat(x, y);
        let marker = new T.Marker(point);
        this.wxMap.addOverLay(marker); // 添加标注点
        
      },
      // 仅更新标注点位置，不发起emit通知父组件
      updateMap() {
        this.wxMap.centerAndZoom(new T.LngLat(this.gpsX, this.gpsY), 8);
        this.getLngLat(new T.LngLat(this.gpsX, this.gpsY));
        // this.getGeocoderFun(this.gpsX, this.gpsY);
      },
      reloadMap(){
        // console.log('reloadMap')
        // this.wxMap = null;
        this.address = '';
        this.gpsX = '';
        this.gpsY = '';
        this.towncode = '';
        // this.throttleFn()
        this.initwxMap();
      },
      // 地址搜索建议
      querySearch(queryString, cb) {
        axios({
          method: "get",
          url: `https://api.tianditu.gov.cn/v2/search?postStr={"keyWord":"${queryString}","level":12,"mapBound":"-180,-90,180,90","queryType":7,"start":0,"count":10}&type=query&tk=${TiandituKey}`,
          // url: `https://api.tianditu.gov.cn/geocoder?postStr={"lon":${lon},"lat":${lat},"appkey":"8a7b9aac0db21f9dd995e61a14685f05","ver":"1"}&type=geocode&tk=3fe9702883d7aade9e3638c1b2779f80`,
          headers: {
            // "Content-Type": "application/x-www-form-urlencoded",
            "Content-Type": "application/json",
          },
        }).then(res => {
          // console.log('TTTTTTTTT====',res)
          let result = res.data.pois
          let resultArr = []
          if(!isArray(result)){
            resultArr = []
          }else{
            result.forEach(item=>{
              resultArr.push({
                ...item,
                value: item.name,
                lng: item.lonlat.split(',')[0],
                lat: item.lonlat.split(',')[1],
              })
            })
          }
          cb(resultArr)
        })
      },
      // 设置标注点，以及根据经纬度查询详细地址
      setMaker(lnglat){
        this.getLngLat(lnglat)

        let x = lnglat.lng;
        let y = lnglat.lat;
        if(isString(lnglat.lng) === false){
          x = lnglat.lng.toFixed(6);
          y = lnglat.lat.toFixed(6);
        }
        this.getGeocoderFun(x, y);
      },
      // 点击输入建议
      handleSelect(item) {
        // console.log(item)
        this.address = item.name
        this.setMaker(item)
        this.wxMap.centerAndZoom(new T.LngLat(item.lng, item.lat));
      },
  },
  mounted() {
    // console.log('mounted')
    this.initwxMap();
    // this.throttleFn = throttle(this.initwxMap,1000) // 节流
  },
};
</script>

<style lang="scss" scoped>
.mapPosition-root {
  .top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .search-input {
      width: 33%;
    }
    .gps {
      margin-left: 20px;
      display: flex;
      justify-content: left;
      .gps-li {
        margin-left: 20px;
      }
    }
    .select-map {
      margin-left: 20px !important;
    }
  }
  .amap {
    height: 300px;
  }
}

::v-deep .el-input {
  width: 100%;
}
</style>
